//
//  BKPlace.m
//  XPhoto
//
//  Created by baboy on 2019/6/21.
//  Copyright © 2019 baboy. All rights reserved.
//

#import "BKPlace.h"
#import "BKHttpRequestManager.h"
#import <BKKit/BKApi.h>

@implementation BKPlace
+(id)search:(nullable NSString*)keyword withLocation:(nullable NSString*)location radius:(NSInteger)radius page:(NSInteger) page callback:(nullable void (^)(id _Nonnull task, id _Nullable json, NSError * _Nullable error))callback{
    NSDictionary *gaodeConf = [BKApi apiForKey:@"gaode"];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:[gaodeConf valueForKey:@"app_key"] forKey:@"key"];
    if (location) {
        [params setValue:location forKey:@"location"];
    }
    if (radius) {
        [params setValue:[NSNumber numberWithInteger:radius] forKey:@"radius"];
    }
    params[@"page"] = [NSNumber numberWithInteger:page];
    params[@"keywords"] = keyword;
    id task = [BKApi request:@"gaode_place_search"
      parameters:params
        callback:^(id  _Nonnull task, id  _Nullable json, NSError * _Nullable error) {
            NSMutableArray *places = nil;
            if(json && [json valueForKey:@"pois"]){
                NSArray *pois = json[@"pois"];
                places = [NSMutableArray array];
                for (NSInteger i = 0; i<pois.count; i++) {
                    NSDictionary *poi = pois[i];
                    BKPlace *place = [[BKPlace alloc] init];
                    id addr = poi[@"address"];
                    place.name = [poi[@"name"] description];
                    place.addr = [addr description];
                    place.location = poi[@"location"];
                    place.provinceName = poi[@"pname"];
                    place.cityName = poi[@"cityname"];
                    place.districtName = poi[@"adname"];
                    if(place.location){
                        NSArray *a = [place.location componentsSeparatedByString:@","];
                        if(a.count==2){
                            place.lng = a[0];
                            place.lat = a[1];
                        }
                    }
                    [places addObject:place];
                }
            }
            if (callback) {
                callback(task, places, error);
            }
        }];
    return task;
}
@end
